package dk.dashboardFP.utils {
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Stage;

	public class DisplayChainTools {

		public static function get_bIsChildOf(doDescendant : DisplayObject, doParent : DisplayObject, bReturnIfEquals : Boolean = true) : Boolean {
			
			//::
			// same as check 
			if (doDescendant == doParent) {
				return bReturnIfEquals;
			}
			
			//::
			// check if doc 
			if (!(doParent is DisplayObjectContainer)) {
				return false;
			}
			
			//::
			// if no parent 
			if (!doDescendant) {
				return false;
			}
			
			//::
			// loop 
			while(doDescendant.parent) {
				if (doDescendant == doParent) {
					return true;
				}
				doDescendant = doDescendant.parent;
			}
			
			return false;
		}

		public static function findAncestorOfType(oDescendentChild : DisplayObject, cAncestorType : Class) : DisplayObject {
			
			var doChild : DisplayObject = oDescendentChild;
			
			if (doChild is cAncestorType) {
				return doChild;
			}
			
			while (doChild.parent) {
				
				if (doChild.parent is cAncestorType) {
					return doChild.parent;
				} else {
					doChild = doChild.parent;
				}
			}
			return null;
		}

		
		public static function get_intNumStepsToStage(doChild : DisplayObject) : int {
			
			if (!doChild.stage) throw new Error("Must be on stage to find number of steps to stage!");

			var doStage : Stage = doChild.stage;
			var intNumSteps:int=0;

			while(doChild != doStage) {
				doChild = doChild.parent;
				intNumSteps++;
			}
			
			return intNumSteps;
		}

		public static function findRoot(doDescendentChild : DisplayObject) : DisplayObject {
			if(!doDescendentChild.parent || !doDescendentChild.stage) {
				return doDescendentChild;
			}
			
			var doChild : DisplayObject = doDescendentChild;
			
			while (doChild.parent) {
				doChild = doChild.parent;
			}
			
			return doChild;
		}	}
}